<?php
error_reporting(0);
require_once "lib/db.class.php";
$link = db::getInstance();
$link->conn->query('set names utf8');
extract($_POST);
class test{

public $var = "1";

public $starttime = '00';
public $endtime = '12:00:00';
public $app_key = '112435';
public $app_secrect = 'S&2r3TT';

/**
* 生成签名
*/
private function createSign($args){
	ksort($args);

	$str = '';
	foreach ($args as $key => $value) {
		$str .= $key.$value;
	}

	$str = 'S&2r3TT' . $str . 'S&2r3TT';

	$sign = strtoupper(md5($str));
	return $sign;
}


/**
 * 模拟post进行url请求
 * @param string $url
 * @param array $post_data
 */
private function request_post($url = '', $post_data = array()) {
    if (empty($url) || empty($post_data)) {
        return false;
    }
    
    $o = "";
    foreach ( $post_data as $k => $v ) 
    { 
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);

    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    
    return $data;
}

/**
* 模拟post提交发送短信
*/
function postSend($arr){
        $url = 'http://smsservice.huoyunren.com/router/rest';
        $post_data['method']  = $arr['method'];
        $post_data['userId']  = $arr['userId'];
        $post_data['mobiles'] = $arr['mobiles'];
        $post_data['content'] = $arr['content'];
        $post_data['app_key'] = $this->app_key;
        $post_data['sign']    = $this->createSign($arr);
        $post_data['timestamp'] = $arr['timestamp'];

        $res = $this->request_post($url, $post_data);       
    }

// 生成验证码
function getVerify(){
    $microtime = microtime(get_as_float);
    $code = rand(0,9).rand(10,99).substr($microtime,-1);
    return $code;
    }

}

$test = new test();

$where = "`phone` ='{$phone}' and date_sub(curdate(), INTERVAL 30 DAY) <= date(`createtime`)";
$fields = "`id`";
$result = $link->select2("query_info", $where, $fields);
if(count($result) >= 3){
	echo 2;
	exit();
}

$verify = $test->getVerify();

$arr = array(
		'app_key' => $test->app_key,
		'method' => 'huoyunren.sms.sender',
		'timestamp' => date('y-m-d h:i:s',time()),
		'userId' => 1000,
		'content' => "验证码：".$verify."，5分钟内有效。",
		'mobiles' => $phone 
		);

//session_start();

setcookie($phone,$verify,time()+300);
setcookie('phone',$phone,time()+300);
//$_SESSION['code'] = $verify;
//$_SESSION['time'] = time();

$res = $test->postSend($arr);//判断验证码是否发生成功
if($res->code==0)
	echo 1;
else
	echo 0;
//echo $verify;
$link->close();
